<template>
  <a-row :gutter="24">
    <a-col :span="6">
      <a-form :model="form1" auto-label-width @submit="handleForm1Submit">
        <a-form-item
          field="typename"
          label="类别名"
          :rules="[{ required: true, message: '类别必填' }]"
        >
          <a-input placeholder="类别名" v-model="form1.typename" />
        </a-form-item>
        <a-form-item
          field="content"
          label="招呼文本"
          :rules="[{ required: true, message: '类别必填' }]"
        >
          <a-textarea
            placeholder="招呼文本"
            v-model="form1.content"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          field="phones"
          label="手机号"
          :rules="[{ required: true, message: '手机号必填' }]"
        >
          <a-textarea
            placeholder="每行一个手机号"
            v-model="form1.phones"
            style="height: 400px"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </a-col>
    <a-col :span="18">
      <div style="padding-bottom: 10px">
        <a-space>
          <a-button
            type="primary"
            status="danger"
            :disabled="selectedKeys.length === 0"
            @click="handleBatchDelete"
          >
            批量删除
          </a-button>
          <a-select
            v-model="searchForm.isok"
            placeholder="是否执行"
            allow-clear
            style="width: 110px"
            @change="handleSearch"
          >
            <a-option :value="1">已执行</a-option>
            <a-option :value="0">未执行</a-option>
          </a-select>
          <a-select
            v-model="searchForm.istask"
            placeholder="是否分配"
            allow-clear
            style="width: 110px"
            @change="handleSearch"
          >
            <a-option :value="1">已分配</a-option>
            <a-option :value="0">未分配</a-option>
          </a-select>
          <a-input-search
            v-model="searchForm.typename"
            placeholder="类别"
            search-button
            @search="handleSearch"
          />
          <a-input-search
            v-model="searchForm.phone"
            placeholder="手机"
            search-button
            @search="handleSearch"
          />
          <a-button style="margin-left: 8px" @click="handleReset"
            >重置</a-button
          >
        </a-space>
      </div>
      <a-table
        row-key="_id"
        :data="phonelist"
        :columns="columns"
        :loading="loading"
        :pagination="{
          total: count,
          current: current,
          pageSize: pageSize,
          showTotal: true,
          showPageSize: true,
        }"
        :row-selection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }"
        v-model:selectedKeys="selectedKeys"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (current - 1) * pageSize }}
        </template>
        <template #nick="{ record }">
          <a-avatar :size="24" shape="square">
            <img alt="avatar" :src="record.avatarMinUrl" />
          </a-avatar>
          {{ record.nick }}
        </template>
        <template #content="{ record }">
          <a-typography-paragraph
            editable
            v-model:editText="record.content"
            @edit-end="handleEditContent(record)"
          >
            {{ record.content }}
          </a-typography-paragraph>
        </template>
        <template #logs="{ record }">
          {{ record.logs }}
        </template>
        <template #istask="{ record }">
          <div v-if="!record.istask">未分配</div>
          <div v-else>
            <a-button-group>
              <a-button>{{ record.triggerTime }}</a-button>
              <a-tooltip content="重置">
                <a-button @click="handleResetTask(record)">
                  <template #icon>
                    <icon-sync />
                  </template>
                </a-button>
              </a-tooltip>
            </a-button-group>
          </div>
        </template>
        <template #isok="{ record }">
          <div>{{ record.submitnum }}次</div>
          <div v-if="record.isfriend">成功</div>
        </template>
      </a-table>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>
  import { ref, watch, reactive } from 'vue';
  import { Message, Modal, TableColumnData } from '@arco-design/web-vue';
  import {
    saveFriendTask,
    delFriendTask,
    getFriendTask,
    editFriendTask,
    resetFriendTask,
  } from '@/api/task';
  // import Task from './friend-task.vue';

  interface FormValues {
    typename: string;
    phones: string;
    content: string;
  }

  const props = defineProps<{
    wxid: string;
  }>();
  const form1 = reactive({
    typename: '',
    phones: '',
    content: '',
  });

  const phonelist = ref([]);
  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const selectedKeys = ref<string[]>([]);
  // 搜索表单数据
  const searchForm = ref({
    phone: '',
    remark: '',
    typename: '',
    isok: undefined,
    istask: undefined,
  });

  const columns: TableColumnData[] = [
    {
      title: '#',
      dataIndex: 'index',
      slotName: 'index',
      width: 70,
    },
    {
      title: '类别',
      dataIndex: 'typename',
      width: 70,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 150,
    },
    {
      title: '昵称',
      slotName: 'nick',
      width: 150,
    },
    {
      title: '招呼',
      slotName: 'content',
      width: 150,
    },
    {
      title: '计划时间',
      slotName: 'istask',
      width: 150,
    },
    {
      title: '执行',
      slotName: 'isok',
    },
  ];

  const fetchPhoneList = async (wxid: string) => {
    loading.value = true;
    try {
      const res: any = await getFriendTask({
        ownerWxid: wxid,
        field: {
          phone: searchForm.value.phone,
          remark: searchForm.value.remark,
          isok: searchForm.value.isok,
          istask: searchForm.value.istask,
        },
        page: current.value,
        pageSize: pageSize.value,
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        phonelist.value = res.data.list;
        loading.value = false;
      } else {
        Message.error(res.msg || '获取任务列表失败');
      }
    } catch (error) {
      console.error('获取任务列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchPhoneList(props.wxid);
  };
  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1; // 切换页面大小时重置为第一页
    await fetchPhoneList(props.wxid);
  };
  // 搜索处理
  const handleSearch = () => {
    current.value = 1; // 重置页码
    fetchPhoneList(props.wxid);
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('请选择要删除的好友');
      return;
    }

    const handleConfirm = async () => {
      try {
        const res: any = await delFriendTask({
          ids: selectedKeys.value,
        });

        if (res.code === 20000) {
          Message.success('批量删除成功');
          selectedKeys.value = []; // 清空选中项
          await fetchPhoneList(props.wxid);
        } else {
          Message.error(res.msg || '批量删除失败');
        }
      } catch (error) {
        Message.error('批量删除失败');
      }
    };

    Modal.warning({
      title: '删除确认',
      content: `确定要删除选中的 ${selectedKeys.value.length} 个手机号吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: handleConfirm,
    });
  };

  const handleForm1Submit = async ({ values }: { values: FormValues }) => {
    // 调用 savetask 接口保存数据
    loading.value = true;
    try {
      const res: any = await saveFriendTask({
        ownerWxid: props.wxid,
        typename: values.typename,
        phones: values.phones,
        content: values.content,
      });
      if (res.code === 20000) {
        Message.success('保存成功');
        fetchPhoneList(props.wxid);
        loading.value = false;
      } else {
        Message.error(res.msg || '保存失败');
      }
    } catch (error) {
      Message.error('保存失败');
    }
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.value = {
      phone: '',
      remark: '',
      typename: '',
      isok: undefined,
      istask: undefined,
    };
    current.value = 1;
    fetchPhoneList(props.wxid);
  };

  const handleEditContent = async (record: any) => {
    try {
      const res: any = await editFriendTask({
        record,
      });

      if (res.code === 20000) {
        Message.success('修改成功');
        await fetchPhoneList(props.wxid);
      } else {
        Message.error(res.msg || '修改失败');
      }
    } catch (error) {
      Message.error('修改失败');
    }
  };

  const handleResetTask = async (record: any) => {
    try {
      const res: any = await resetFriendTask({
        record,
      });

      if (res.code === 20000) {
        Message.success('重置成功');
        await fetchPhoneList(props.wxid);
      } else {
        Message.error(res.msg || '重置失败');
      }
    } catch (error) {
      Message.error('重置失败');
    }
  };

  watch(
    () => props.wxid,
    async (newVal) => {
      if (newVal) {
        await fetchPhoneList(newVal);
      }
    },
    { immediate: true }
  );
</script>
